﻿using System;
using System.Web.Mvc;
using ZBJF.Warranty.BLL;
using ZBJF.Warranty.Common.Enums;
using ZBJF.Warranty.Common.Enums.System;
using ZBJF.Warranty.Model;
using ZBJF.Warranty.WebProvider;
using ZBJF.Warranty.WebProvider.Filter;

namespace ZBJF.Warranty.AdminSite.Controllers
{
    public class LoginController : BaseController
    {
        [LoginFilter(IsCheck = false)]
        [AuthenticationFilter(NeedAuthentication = false)]
        public ActionResult Index()
        {
            return View();
        }

        [LoginFilter(IsCheck = false)]
        [AuthenticationFilter(NeedAuthentication = false)]
        [AllowAnonymous]
        public ActionResult NoAuthory()
        {
            return View();
        }

        [HttpPost]
        [LoginFilter(IsCheck = false)]
        [AuthenticationFilter(NeedAuthentication = false)]
        [ValidateAntiForgeryToken]
        public ActionResult Index(SystemUser model)
        {
            ResponseResult responseResult = new ResponseResult();
            var flag = false;
            var user = ServiceFactory.SystemUserServiceInstance.Login(model.UserAccount, model.Password, ApplicationType.AdminSite, out flag);
            if (flag)
            {
                CurrentUser = user;
                //Session["User_ID"] = user.ID;
                CookiesHelper.Instance.SetLoginSession(user.UserAccount);
                CookiesHelper.Instance.SetLoginUserTypeSession(user.BelongApplicationType);
                return RedirectToAction("Index", "Home");
            }
            else
            {
                CurrentUser = null;
                CookiesHelper.Instance.ClearLoginSession();
                responseResult.Message = "用户名或者密码无效！";
                TempData["ResponseResult"] = responseResult;
                return View();
            }
        }

        [HttpGet]
        [AllowAnonymous]
        [AuthenticationFilter(NeedAuthentication = false)]
        public ActionResult LogOut()
        {
            SystemUser user = ServiceFactory.SystemUserServiceInstance.Load(CurrentUser.ID);
            user.IsCheckOnline = 0;
            bool re = ServiceFactory.SystemUserServiceInstance.UpdateEntities(user);
            CurrentUser = null;
            CookiesHelper.Instance.ClearLoginSession();
            return RedirectToAction("Index", "Login");
        }


    }
}